package com.bed.lovewithpatientbed.controller;

import com.bed.lovewithpatientbed.common.LoginSubjectType;
import com.bed.lovewithpatientbed.common.token.CustomUsernamePasswordToken;
import com.bed.lovewithpatientbed.pojo.User;
import com.bed.lovewithpatientbed.service.IUserService;
import com.bed.lovewithpatientbed.util.KaptchaUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author xuxiaoding
 * @version 1.0.0
 * @ClassName UserLoginController.java
 * @Description 用户登录Controller
 */
@Slf4j
@Controller
public class UserLoginController {

    private IUserService userService;

    @Autowired
    public void setUserService(IUserService userService) {
        this.userService = userService;
    }

    @PostMapping("/userLogin")
    @ResponseBody
    public Map<String, Object> userLogin(HttpSession httpSession, User user, String captcha) {
        Map<String, Object> responseMap = new HashMap<>();

        if (user == null
                || user.getUserPhone() == null || "".equals(user.getUserPhone())
                || user.getUserPassword() == null || "".equals(user.getUserPassword())) {
            responseMap.put("result", false);
            responseMap.put("errorMsg", "登录请求参数错误");
            return responseMap;
        }

        // 获取验证码
        String verificationCode = (String) httpSession.getAttribute(KaptchaUtil.KAPTCHA_SESSION_KEY);
        if (verificationCode == null || "".equals(verificationCode)) {
            responseMap.put("result", false);
            responseMap.put("errorMsg", "验证码读取错误");
            return responseMap;
        }

        // 验证码校验
        if (!KaptchaUtil.checkVerificationCode(verificationCode, captcha)) {
            responseMap.put("result", false);
            responseMap.put("errorMsg", "验证码输入错误");
            return responseMap;
        }

        // 获取主体
        Subject subject = SecurityUtils.getSubject();
        // 生成token
        CustomUsernamePasswordToken token =
                new CustomUsernamePasswordToken(user.getUserPhone(), user.getUserPassword(),
                        LoginSubjectType.ORDINARY_USER);

        try {
            // 登录认证
            subject.login(token);
            responseMap.put("result", true);
        } catch (UnknownAccountException e) {
            e.printStackTrace();
            responseMap.put("result", false);
            responseMap.put("errorMsg", "用户名错误");
        } catch (IncorrectCredentialsException e) {
            e.printStackTrace();
            responseMap.put("result", false);
            responseMap.put("errorMsg", "密码错误");
        }catch (Exception e){
            e.printStackTrace();
            responseMap.put("result", false);
            responseMap.put("errorMsg", "登陆失败");
        }

        log.info("{} 请求登录，账号为：{}，登录结果：{}，失败原因：{}",
                LoginSubjectType.ORDINARY_USER.toString(),
                user.getUserPhone(), responseMap.get("result"), responseMap.get("errorMsg"));

        return responseMap;
    }

    /**
     * @title userRegister
     * @description 用户注册
     * @author xuxiaoding
     * @param user 注册信息封装对象
     * @param bindingResult 绑定校验，
     * @return void
     * @throws
     */
    @PostMapping("/userRegister")
    @ResponseBody
    public Map<String, Object> userRegister(@Validated User user, BindingResult bindingResult) {
        Map<String, Object> responseMap = new HashMap<>();

        if (user == null) {
            // 如果 user 为空， 直接返回
            responseMap.put("result", false);
            return responseMap;
        }

        // 如果存在错误信息
        if (bindingResult.hasErrors()) {
            responseMap.put("registerResult", false);
            /*
             转存错误信息
             */
            List<String> errorMsg = new ArrayList<>();
            List<ObjectError> allErrors = bindingResult.getAllErrors();
            for (ObjectError error : allErrors) {
                errorMsg.add(error.getDefaultMessage());
            }
            responseMap.put("errorMsg", errorMsg);
        } else {
            responseMap = userService.register(user);
        }

        System.out.println(responseMap);
        return responseMap;
    }


}
